﻿using Autofac;
using Autofac.Core.Lifetime;
using Domain.IServices;
using Domain.Models;
using GitSyncApp.IServices;
using GitSyncApp.Models;
using GitSyncApp.Views.Shared;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace GitSyncApp.Views
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        /// <summary>
        /// 是否自动同步中
        /// </summary>
        private bool isSyncing = false;

        private readonly IDomainService<GitLibaray> domainService;
        private readonly ISyncJobService jobService;

        public MainWindow(IDomainService<GitLibaray> domainService, ISyncJobService jobService)
        {
            this.domainService = domainService ?? throw new ArgumentNullException(nameof(domainService));
            this.jobService = jobService ?? throw new ArgumentNullException(nameof(jobService));

            InitializeComponent();

            Task.FromResult(DataBindListViewAsync());
        }
        
        private async Task DataBindListViewAsync()
        {
            var gits = await domainService.ToListAsync();

            if (gits.Count == 0)
                return;

            list.Items.Clear();

            foreach(var git in gits)
            {
                list.Items.Add(new RepositoryModel { Id = git.Id, Name = git.Name, Url = git.RepositoryUrl.AbsoluteUri });
            }
        }

        private void NewRepository_Click(object sender, RoutedEventArgs e)
        {
            RepositoryWindow repository = new RepositoryWindow();
            repository.ShowDialog();
        }

        private void AutoSync_Click(object sender, RoutedEventArgs e)
        {
            isSyncing = !isSyncing;
            autoSync.Content = isSyncing ? "停止自动同步" : "开始自动同步";

            if (isSyncing)
            {
                if(jobService.JobFactory.Count != list.Items.Count)
                {
                    var result = jobService.CreateCollectionAsync(domainService.ToListAsync().Result).Result;
                    if (!result.Success)
                    {

                    }
                }
            }
        }
    }
}
